package sicnu.cs.ich.activity.util;

import lombok.RequiredArgsConstructor;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
import sicnu.cs.ich.activity.domain.CensorWords;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;

/**
 * @author 黎琦
 * @date 2021/12/21 22:52
 **/
@Component
@RequiredArgsConstructor
public class SensitiveWordUtil {
    /**
     * 初始化
     */
    private static StringBuilder replaceAll;
    private final String replceStr = "*";
    private final int replceSize = 500;
    private static List<String> arrayList;
    private final MongoTemplate mongoTemplate;


    /**
     * @param str 将要被过滤信息
     * @return 过滤后的信息
     */
    public static String filterInfo(String str) {
        StringBuilder buffer = new StringBuilder(str);
        HashMap<Integer, Integer> hash = new HashMap<>(arrayList.size());
        String temp;
        for (String s : arrayList) {
            temp = s;
            int findIndexSize = 0;
            for (int start = -1; (start = buffer.indexOf(temp, findIndexSize)) > -1; ) {
                findIndexSize = start + temp.length();//从已找到的后面开始找
                Integer mapStart = hash.get(start);//起始位置
                if (mapStart == null || (mapStart != null && findIndexSize > mapStart))//满足1个，即可更新map
                {
                    hash.put(start, findIndexSize);
                }
            }
        }
        Collection<Integer> values = hash.keySet();
        for(Integer startIndex : values)
        {
            Integer endIndex = hash.get(startIndex);
            buffer.replace(startIndex, endIndex, replaceAll.substring(0,endIndex-startIndex));
        }
        hash.clear();
        return buffer.toString();
    }

    /**
     *   初始化敏感词库，只在项目启动时执行一次
     */
    public void initializationWord() {
        replaceAll = new StringBuilder(replceSize);
        replaceAll.append(String.valueOf(replceStr).repeat(Math.max(0, replceSize)));
        arrayList = mongoTemplate.findAll(CensorWords.class).get(0).getWord();
    }
}
